/* eslint-disable space-before-function-paren */
<template>
  <div>
    <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload">
      <el-progress v-if="percent && percent < 100" type="circle" :percentage="percent" />
      <img v-if="value && percent===0" :src="value" class="avatar">
      <i v-show="!percent" v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDTjkW2HFwMWP1MPBguqWv3uUosfCTTCep', // 身份识别ID
  SecretKey: 'xe4D6i37vSiiV1GEuKTKuEH3XkgLnzva' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    // 从父组件传递过来的v-model对应的值
    value: { type: String, default: '' }
  },
  data() {
    return {
      // imageUrl: '',
      percent: 0
    }
  },
  methods: {
    upload(res) {
      if (!res.file) return
      // 执行上传操作
      cos.putObject({
        Bucket: 'dahai-1306051795', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file, // 上传文件对象
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))
          this.percent = parseInt(progressData.percent * 100)
        }
        // eslint-disable-next-line space-before-function-paren
      }, async (err, data) => {
        console.log(err || data)
        // 上传成功之后
        if (data.statusCode === 200) {
          // this.value = `https://${data.Location}`
          this.percent = 0
          this.$emit('input', `https://${data.Location}`)
        }
      })
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('只能上传图片格式的文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M // 如果这里返回的是 false 则会阻止文件上传
    }
  }
}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-progress-circle {
  width: 178px !important;
  height: 178px !important;
}
/* .el-upload {
  height: 153px;
} */
</style>
